#!/usr/bin/perl -w 

### Notes:
# The -T for security check would help to protect the script but was giving error and was removed.
# The arguments been used as parameterson external commands/scripts. For the arguments only hexadecimal and - are allowed. Feel free ADD extra protectiong.

#TODO - Perhaps we should check if the transcoding command (conv.pl "input.mp4" ...) executed without errors (Maybe pass the output on) 
# This script needs to un during system start up since it assumes all transcoding and downloadings were stopped

# Should we check for lsof existence?

use POSIX qw(strftime);
use Fcntl qw(:DEFAULT :flock);
use FCTranscode;


### Start og main program ###

# TODO Usage
# Process command line argument arguments 
#if ($#ARGV!=1) {
#	print "Usage: $0 batchid jobid";
#	exit 0;
#}

# Reading  collector status file 
# Remember! collector uses ' instead of "

open(FH, "<", $collector_file); #TODO - Handle in case there is no collector_file
                                #which would not be good since there wouldn't be request if there is no collector/is empty
flock FH, LOCK_SH;
@lines = <FH>;
flock FH, LOCK_UN;
close FH;

foreach $line (@lines) {

        $line =~ /remote_id=\'([\w\.\-]+)\'/;
        $remote_id = $1;

        #if ($line =~ /jobid=\'([[:xdigit:]-]{36})\'/){
        #       $jobid = $1; }
        #elsif ($line =~ /jobid=\'(\/[\w\/\.]+\.\d+\.status)\'/){
        #       $jobid = $1; }

        $line =~ /jobid=\'([^\']+)\'/;
        $jobid = $1;

        #if ($line =~ /batchid=\'([[:xdigit:]-]{36})\'/){
        #       $batchid = $1; }
        #elsif ($line =~ /batchid=\'(n\/a)\'/){
        #        $batchid = $1; }

        $line =~ /batchid=\'([^\']+)\'/;
        $batchid = $1;

        $line =~ /col_status=\'([\w\:\ ]+)\'/;
        $col_status = $1;

        $line =~ /transcoder=\'([\w]+)\'/;
        $transcoder = $1;

        $line =~ /status=\'([^\']+)\'/;
        $status = $1;

        $line =~ /percentComplete=\'([^\']{1,3})\'/;
        $percomp = $1;

        #$line =~ /timeRemaining=\'([\w\(\)\ \.]+)\'/;
        $line =~ /timeRemaining=\'([^\']+)\'/;
        $timerem = $1;

        #$line =~ /timeElapsed=\'([\w\(\)\']+)\'/;
        $line =~ /timeElapsed=\'([^\']+)\'/;
        $timeelap = $1;

	$line =~ /input=\'([^\']+)\'/;
	$input_file = $1;

        $line =~ /output=\'([^\']+)\'/;
        $output_file = $1;

	$line =~ /format=\'([^\']+)\'/;
	$format = $1;

        $collector_jobs_status{ $remote_id } = {
                jobid => $jobid,
                batchid => $batchid,
                col_status => $col_status,
                transcoder => $transcoder,
                status => $status,
                percomp => $percomp,
                timerem => $timerem,
                timeelap => $timeelap,
		input => $input_file,
                output => $output_file,
		format => $format,
                }
}
#use Data::Dumper;
#print Dumper(%collector_jobs_status);

foreach my $key (keys %collector_jobs_status) {

	if ($collector_jobs_status{$key}->{'col_status'} eq 'finished'
	|   $collector_jobs_status{$key}->{'col_status'} eq 'cancelled') { next; }
	elsif ($collector_jobs_status{$key}->{'col_status'} eq 'downloading'
	|      $collector_jobs_status{$key}->{'col_status'} eq 'waiting') {
		write_log("Found $key ".$collector_jobs_status{$key}->{'col_status'});
		#my $remote_id = $collector_jobs_status{$key}->{'remote_id'};
		my $input_file = $collector_jobs_status{$key}->{'input'};
		my $format = $collector_jobs_status{$key}->{'format'};
		write_log("    Remote_id: $key\n    Input: $input_file\n    Format: $format");

		$req_struct{$input_file} .= "$format:$key&";
		remove_remote_id($key);
	}
	else { write_log('Unknown col_status value: '.$collector_jobs_status{$key}->{'col_status'}." for remote_id $key"); }
		
}

#use Data::Dumper;
#print Dumper(%req_struct);
print `cat status/collector_status`;

foreach my $input_file (keys %req_struct) {
	
	$pairs_str = $req_struct{$input_file};
	chop($pairs_str);	# chop since the line always comes with & at the end
	$cmd = "$conv_loc \"$input_file\" \"$pairs_str\"";
	write_log($cmd);
	$output = `$cmd`;
	print $output;
}

